<!--
 * @Description: 
 * @Author: zhuhao
 * @Date: 2020-11-12 11:26:24
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2020-12-28 11:57:50
-->
<template>
<div class="page_box">

  <div class="statis_mian" v-loading='tableLoading'>
      
        <div class="page_tabs">
            工作日报
        </div>
        <div class="head_btn">
            <el-form class="form" inline label-width="auto" size="mini">
                <el-form-item label="市:">
                    <el-select
                        v-model="cityCode"
                        placeholder="请选择"
                        @change="cityChange"
                        :disabled='isCity'
                        style="width:200px"
                        clearable
                        >
                        <el-option
                            v-for="item in cityData"
                            :key="item.city_code"
                            :label="item.city_name"
                            :value="item.city_code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区县:">
                     <el-select
                        v-model="countyCode"
                        placeholder="请选择"
                        @change="countyChange"
                        :disabled='isCounty' 
                        style="width:200px"

                        clearable
                        >
                            <el-option
                                v-for="item in countyData"
                                :key="item.county_code"
                                :label="item.county_name"
                                :value="item.county_code"
                            >
                    </el-option>
                </el-select>
                </el-form-item>
                <el-form-item label="营业部:">
                    <el-select 
                        clearable
                        style="width:200px"
                        v-model="empDeptCode" 
                        :disabled='isDept' 
                        placeholder="请选择">
                        <el-option
                            v-for="item in deptData"
                            :key="item.dept_code"
                            :label="item.dept_name"
                            :value="item.dept_code"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="日期选择:">
                    <el-date-picker
                        v-model="dateArr"
                        type="daterange"
                        
                        :clearable='false'
                        :unlink-panels='true'
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        style="width:300px"
                        :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item> 
                    <el-button  
                        type="primary"  
                        @click="getDeptDateList">
                        查询
                    </el-button>
                    
                    <el-button  
                        v-if="isDept"   
                        type="primary" 
                        style="margin-left:20px"
                        @click="monthDialogVisible=true;getMonthPlanList()">
                        月计划配置
                    </el-button>
                </el-form-item>
            </el-form>  
        </div>
      

        <el-table
            :data="deptDayList" 
            stripe
            border
            style="width: 100%">
             <el-table-column label="省"  prop="provinceName"/>
            <el-table-column label="市" prop="cityName"/>

            <el-table-column label="区/县" prop="countyName"> </el-table-column>
            <el-table-column label="营业部" min-width="300"  prop="deptName"></el-table-column>
            <el-table-column label="日期" prop="statDate"></el-table-column>

                <!-- v-if="isDept" -->
               <el-table-column label="操作"   >
                <template slot-scope="{row}">
                    <div>
                        <el-button
                            size="mini" type="text"
                            @click="openDeteal(row)">
                          查看详情
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>  
        <div class="pageBox">
            <el-pagination
                background
                @current-change="deptPageChange"
                :current-page.sync="deptPageNum"
                :page-size="10"
                layout="prev, pager, next, jumper,total"
                :total="deptTotal"
            >
            </el-pagination>
        </div> 

        
    <!-- 
        营业部某日详情
     -->
      <el-dialog
        :title="deptDetailStr+'收入汇总表'"
        :visible.sync="detailVisible"
        modal-append-to-body
        append-to-body
        width="80%"
        >
          
        <el-table
            :data="deptTableData" 
            stripe
            border
            style="width: 100%">
            <el-table-column label="收寄员" fixed prop="userName"/>
            <el-table-column label="月计划" prop="monthPlanedIncome"/>

            <el-table-column label="标准快递">
                <el-table-column label="件数" prop="standardMailCount"/>
                <el-table-column label="收入" prop="standardMailIncome"/>
                <el-table-column label="当月完成件数" prop="standardMailCompletedCount"/>
                <el-table-column label="当月完成收入" prop="standardMailCompletedIncome"/>

            </el-table-column>
            <el-table-column label="散件计划">
                <el-table-column label="散户件数" prop="fragmentedMailCount"/>
                <el-table-column label="收入" prop="fragmentedMailIncome"/>
                <el-table-column label="当月完成件数" prop="fragmentedMailCompletedCount"/>
                <el-table-column label="当月完成收入" prop="fragmentedMailCompletedIncome"/>

            </el-table-column>
            <el-table-column label="快递包裹">
                <el-table-column label="件数" prop="expressCount"/>
                <el-table-column label="收入" prop="expressIncome"/>
                <el-table-column label="当月完成件数" prop="expressCompletedCount"/>
                <el-table-column label="当月完成收入" prop="expressCompletedIncome"/>
            </el-table-column>
            <el-table-column label="走访客户数">
                <el-table-column label="当日走访客户数" prop="dailyVisit"/>
                <el-table-column label="当月走访客户数" prop="monthlyVisit"/>

            </el-table-column>
            <el-table-column label="投递数据">
                <el-table-column label="当日投递总数" prop="dailyDelivery"/>
                <el-table-column label="当月投递总数" prop="monthlyDelivery"/>
            </el-table-column> 
            <el-table-column label="操作"  v-if="isDept" >
                <template slot-scope="{row}">
                    <div>
                        <el-button
                        v-if="row.isVacation==0"
                            size="mini" type="text"
                            @click="openEdit(row)">
                        修改保存
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>  
        <div class="pageBox">
            <el-pagination
                background
                @current-change="handleCurrentChangeLantou"
                :current-page.sync="currentPageLantou"
                :page-size="10"
                layout="prev, pager, next, jumper,total"
                :total="totalPageLantou"
            >
            </el-pagination>
             <el-button  
                v-if="deptTableData.length"  
                size="mini"
                type="success" 
                style="margin-left:20px"
                @click="exportTable">
                导出
            </el-button>
        </div>
        
        </el-dialog>

     <el-dialog
        :title="editTit+'填报记录'"
        :visible.sync="editVisible"
        modal-append-to-body
        append-to-body
        center
        width="50%"
    > 
        <editForm ref="editForm" :form='editForm'/>
        <div slot="footer" class="dialog-footer"> 
            <el-button v-loading='editLoading' type="primary" @click="saveEdit">修改保存</el-button>
            <el-button @click="editVisible=false">取消</el-button>
        </div>
    </el-dialog>

   <!-- 月计划配置 -->
        <!-- :title="userInfo.salesDeptName+'月计划配置'" -->
    <el-dialog
        :title="'月计划配置'"
        :visible.sync="monthDialogVisible"
        modal-append-to-body
        append-to-body
        width="80%"
    >   
        <div  v-loading='userLoading'>
            <div class="head_btn">
                <el-date-picker
                    v-model="month"
                    type="month"
                    size="mini"
                    :clearable="false"
                    placeholder="选择月">
                </el-date-picker>

                <el-button 
                    size="mini"
                    type="primary" 
                    style="margin-left:20px" 
                    @click="getMonthPlanList"
                    >
                    查询
                </el-button>
            </div>
        <el-table
            stripe
            border
            row-key='userCode'
            :data="userData.slice((userCurrentPage-1)*userPageSize,userCurrentPage*userPageSize)"
            ref="monthPlan" 
            style="width: 100%">
            <el-table-column type="selection" reserve-selection /> 
            <el-table-column label="收寄员"  prop="userName"/>
            <el-table-column label="月计划"  prop="planAmount">
                <template slot-scope="{row}"> 
                    <el-input-number :precision="2" :min="0" v-model="row.planAmount"></el-input-number>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="{row}">
                    <div>
                        <el-button
                             type="text"
                            @click="saveOne(row)">
                          修改
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>
            <div class="pageBox">
                <el-pagination
                    background
                    @current-change="userCurrentChange"
                    :current-page.sync="userCurrentPage"
                    :page-size="10"
                    layout="prev, pager, next, jumper,total"
                    :total="userTotalPage"
                >
                </el-pagination>
            </div>
    </div>
        <div slot="footer" class="dialog-footer">
            <!-- <el-button type="primary" v-if="isEdit" @click="monthDialogVisible=false">保存修改</el-button> -->
            <!-- <el-button type="primary" v-else @click="monthDialogVisible=false">确定</el-button> -->
            <el-button size="mini" type="primary" @click="saveMonthPlan">保存所有</el-button>
            <el-button size="mini" @click="monthDialogVisible=false">取消</el-button>
        </div>

    </el-dialog>
  </div>
</div>

</template>

<script>
import API from "@/apis/jxyzwg.js";
import storage from 'good-storage'
import editForm from './edit-form.vue'

export default {
    name:'DailyStatisticalReports',
    components:{editForm},
    data() {
        return {
            currentPageLantou:1,
            totalPageLantou:0,
            // currentPageDialog:1,
            // totalPageDialog:0,
            options:[],
            userInfo:{},
            tableData:[],
            dateStr:new Date(),
            dateArr:[new Date(),new Date()],
            deptStr:'城西', 
            deptTableData:[],
            month:new Date(),
            monthDialogVisible:false,//月计划配置
            isEdit:false,//月计划配置是否属于修改
            userData:[],
            userPageSize:10,
            userCurrentPage:1,
            userTotalPage:0,
            userLoading:false,
            // selectDeptCode:'',
            pickerOptions:{
                disabledDate(time) {
                    return time.getTime() > Date.now();
                }
            },

            detailVisible:false,
            defaultCode:null,

            deptPageNum:1,
            deptTotal:0,
            deptDayList:[],
            detailDeptCode:null,
            deptDetailStr:'',
            editVisible:false,
            editForm:{},
            editTit:'',
            editLoading:false,
            cityCode:'',
            countyCode:'',
            empDeptCode:'',
            isCity:false,
            isCounty:false,
            isDept:false,
            cityData: [],
            countyData: [],
            deptData: [],
            tableLoading:false
        }
    },
     
    created() { 
        //测试生数据
    //     window._adoPremise.user = {
    //       "id": "ce5b9876-f189-4edb-a953-9496a9ef2866",
    //       "name": "03589163",
    //       "roles": [
    //           {
    //               areaLevel: "{$grid$}",
    //               city: null, 
    //               instanceRoleName: "营业部级管理员", 
    //               level: "4",
    //               name: "中国邮政集团有限公司宜春市袁州区寄递事业部城西营业部",
    //               pathCode: "360000,360900,360902,33600035", 
    //               targetId: "33600035", 
    //           },
    //           {
    //               areaLevel: "{$grid$}",
    //               city: null, 
    //               instanceRoleName: "区县级管理员", 
    //               level: "4",
    //               name: "中国邮政集团有限公司宜春市袁州区寄递事业部城西营业部",
    //               pathCode: "360000,360900,360902", 
    //               targetId: "360902", 
    //           },
    //           {
    //               areaLevel: "{$branch$}",
    //               city: null, 
    //               instanceRoleName: "市级管理员", 
    //               level: "1", 
    //               pathCode: "360000,360900", 
    //               targetId: "360900",  
    //           },
    //               {
    //                   level:1,
    //                   instanceRoleName: "省级管理员",
    //                   targetId: "360000",
    //                   pathCode: "360000"
    //               }
    //       ],
    //       "currentRole": {
    //           "regionCode": "33600035",
    //           "roleCode": "de620ac1-0c56-4128-a9c9-46aae90e1be4",
    //           "name": "营业部级管理员"
    //       },
         
    //   }
        this.userInfo=window._adoPremise.user 
        let fristDay=new Date(new Date().getFullYear()+'-'+(new Date().getMonth()+1)+'-'+'01')
        this.dateArr=[fristDay,new Date]
        this.getMaxRole()
    }, 
    methods: {
        getMaxRole(){
              let maxRole={}
         maxRole=this.userInfo.roles.filter(function(item){
           return item.instanceRoleName=="省级管理员"
         })
         if (!maxRole.length) {
           maxRole=this.userInfo.roles.filter(function(item){
           return item.instanceRoleName=="市级管理员"
          })
         }
         if (!maxRole.length) {
           maxRole=this.userInfo.roles.filter(function(item){
           return item.instanceRoleName=="区县级管理员"
          })
         }
         if (!maxRole.length) {
           maxRole=this.userInfo.roles.filter(function(item){
           return item.instanceRoleName=="营业部级管理员"
          })  
         }  
         
        if (maxRole.length) {
          let deptArr=maxRole[0].pathCode.split(',')
          
            deptArr.map((item,i)=>{
                if (i==1) {
                  this.isCity=true 
                  this.cityCode=item
                  this.cityChange(this.cityCode)

                }else if (i==2) {
                  this.isCounty=true 
                  this.countyCode=item
                  this.countyChange(this.countyCode)
                } else if (i==3) {
                  this.isDept=true 
                  this.empDeptCode=item
                }
            })
            
        } 
            console.log(this.cityCode);
            // this.getOrgList()
            this.getCityList(360000);

        },
        getOrgList(){
            API.getOrgList().then(res=>{
              
                if (res.code==200) {
                    if (this.isDept) { 
                        this.userInfo.salesDeptName=''
                        res.rows.map(item=>{
                            if (item.code==this.userInfo.salesDeptCode) {
                               
                                this.userInfo.salesDeptName=item.name
                            }
                        })
                    }
                    this.options=this.getTreeData(res.rows,res.rows[0].parentCode)
                    // if (this.userInfo.level<4) { 
                    //         this.defaultCode=this.options[0]
                    //         for (let index = 0; index < 4-this.userInfo.level; index++) {
                    //             this.defaultCode=this.defaultCode.children[0]
                    //         }
                    //         this.selectDeptCode=this.defaultCode.code
                            
                    // } 
                     this.getDeptDateList()
 
                } else {
                    this.$message.warning('查询部门数据失败')
                    
                }
            })
        },
        getMonthPlanList(){
            let params={
                deptCode:this.userInfo.salesDeptCode,
                planMonth:new Date(this.month).getFullYear()+'-'+(new Date(this.month).getMonth()+1)
            }
            this.userLoading=true
            this.userData=[]
            this.userTotalPage=0
            API.getMonthPlanList(params).then(res=>{
                console.log(res); 
                if (res.code==200) { 
                    this.userData=res.rows
                    this.userTotalPage=res.total
                    // this.isEdit=true
                    this.userLoading=false

                } else {
                    this.userLoading=false
                    this.$message.warning('查询数据失败')
                }
            })
        },

        getTableList(){
            let paramas={
                pageSize:10,
                pageNum:this.currentPageLantou,
                deptCode:this.detailDeptCode,
                statDate:this.setTime(this.dateStr) 
            }
            this.deptTableData=[] 
             API.getIncomeList(paramas).then(res=>{
               
                 if (res.code==200) {
                     this.deptTableData=res.rows
                     this.totalPageLantou=res.total
                 } else {
                    this.$message.warning('查询数据失败')
                     
                 }
             })
        },
         //分页器当前页改变
        handleCurrentChangeLantou(val) {
            this.currentPageLantou = val;
            this.getTableList()
        },
        userCurrentChange(val){
            this.userCurrentPage = val;
        },
        
        
        //
        saveMonthPlan(){
            console.log(this.$refs['monthPlan'].selection);
            if (this.$refs['monthPlan'].selection.length) {
                
                API.batchMonthPlan(this.$refs['monthPlan'].selection).then(res=>{
               
                    this.getMonthPlanList()

                })
            } else {
                    this.$message.warning('请选择')
                
            }
        },
        saveOne(row){
            console.log(row);
            if (row.id==0) {
                this.addMonth(row)
            }else {
                this.editMonth(row)
            }
        },
        addMonth(params){ 
            let monthPlan=params
            this.userLoading=true
            API.addMonthPlan(monthPlan).then(res=>{
                if (res) {
                this.$message.success('保存数据成功')
                this.userLoading=false
                    
                }else {
                this.userLoading=false
                this.$message.warning('保存数据失败')}
             })
        },
        editMonth(params){ 
            let monthPlan=params
            this.userLoading=true
            API.eidtMonthPlan(monthPlan).then(res=>{
                 if (res) {
                    this.$message.success('修改数据成功')
                    this.userLoading=false
                     
                 }else {
                    this.userLoading=false
                    this.$message.warning('修改数据失败')}
             })
        },

        //处理部门数据
        getTreeData(source,parentId ) {
          const cloneData = JSON.parse(JSON.stringify(source)) // 对源数据深度克隆
         
          return cloneData.filter(father => {
            // 循环所有项，并添加children属性
            const branchArr = cloneData.filter(child => father.code=== child.parentCode) // 返回每一项的子级数组
            branchArr.length > 0 ? (father.children = branchArr) : '' // 给父级添加一个children属性，并赋值
            return father.parentCode=== parentId // 返回第一层
          })
        },
        //查询按钮
        selectChange(){
            this.currentPageLantou=1
            this.getTableList()
        },
         
        //导出
        exportTable(){
            
            let herf=window._adoPromiseBaseUrl+"/jxyzwg/income/summarys/download?deptCode="+this.detailDeptCode+'&statDate='+this.setTime(this.dateStr) 
           console.log(herf);
           window.open(herf)
        //    let a = document.createElement('a')
        //     document.body.appendChild(a)
        //     a.href =herf 
        //     a.click() 
        },

        //打开某日详情

        openDeteal(row){
            this.detailVisible=true
            console.log(row);
            this.detailDeptCode=row.deptCode
            this.dateStr=row.statDate
            this.deptDetailStr=row.deptName
            this.getTableList()
        },

        //获取某营业部时间区间数据
        getDeptDateList(){
            
            let params={
                // deptCode:this.selectDeptCode,
                startDate:this.setTime(this.dateArr[0]),
                endDate:this.setTime(this.dateArr[1]),
                pageSize:10,
                pageNum:this.deptPageNum
            }   
            params.cityCode=this.cityCode
            params.countyCode=this.countyCode
            params.deptCode=this.empDeptCode
                         
            this.deptDayList=[]
            this.tableLoading=true
            API.getDateList(params).then(res=>{
                console.log(res);
                if (res.code==200&&res.rows) {
                    this.deptDayList=res.rows.map(item=>{
                        item.statDate=this.setTime(item.statDate)
                        return item
                    })
                    this.deptTotal=res.total
                } else {
                    this.$message.warning('查询数据失败')
                    
                }
                this.tableLoading=false

            })
        },
        deptPageChange(val){
            console.log(val);
            this.deptPageNum=val
            this.getDeptDateList()
        },

        //设置时间格式
        setTime(val){
            let obj=new Date(val)
            let dayStr=obj.getDate()<10?'0'+obj.getDate():obj.getDate()
            return obj.getFullYear()+'-'+(obj.getMonth()+1)+'-'+dayStr
        },
        openEdit(row){
            console.log(row);
            this.editForm=JSON.parse(JSON.stringify(row))
            this.editVisible=true
            this.editTit=row.userName+'-'+this.setTime(row.statDate)
        },
        //保存修改
        saveEdit(){
             
            this.$refs['editForm'].$refs['form'].validate((valid) => {
                if (valid) {
                    let parmas={
                        dailyDelivery: 0,
                        dailyVisit: 0,
                        deptCode: "",
                        expressCount: 0,
                        expressIncome: 0,
                        fragmentedMailCount: 0,
                        fragmentedMailIncome: 0,
                        id: 0,
                        standardMailCount: 0,
                        standardMailIncome: 0,
                        statDate: "",
                        userCode: "",
                        userName: ""
                    }
                        for (const key in parmas) {
                             parmas[key]=this.editForm[key]
                        }
                        this.editLoading=true
                        API.eidtHistory(parmas).then(res=>{
                                console.log(res);
                                if (res) {
                                        this.$message.success('修改成功')
                                        this.editVisible=false
                                        this.getTableList()
                                        this.editLoading=false  

                                } else {
                                        this.$message.warning('修改失败')
                                        this.editLoading=false
                                    
                                }
                            }) 
                        }else{
                            this.$message.warning('请完整填写')
                            return false; 
                        }
                 })
        },

             // 获取城市数据列表
            getCityList(orgCode) {
            this.tableLoading=true
            API.getDepartmentListByCode({ orgCode }).then((res) => {
                this.cityData = this.unique(res.data, "city_code"); 
                     this.getDeptDateList()
                });
                    this.tableLoading=false

            },
        // 切换城市获取区县列表
        cityChange(orgCode) {
        this.tableLoading=true
        API.getDepartmentListByCode({ orgCode: this.cityCode }).then(
            (res) => {
            if (!this.isCity) {
                this.countyCode = "";
                this.empDeptCode = "";
            }
            this.countyData = this.unique(res.data, "county_code");
                    this.tableLoading=false
            }
        );
        },
        // 切换城市获取段道列表
        countyChange(orgCode) {
        this.tableLoading=true
        API.getDepartmentListByCode({ orgCode: this.countyCode }).then(
            (res) => {
            if (!this.isCounty) {
                this.empDeptCode = "";
            }
            this.deptData = this.unique(res.data, "dept_code");
                    this.tableLoading=false
            }
        );
        },
        // 数组去重
        unique(arr, code) {
        const res = new Map();
        return arr.filter((arr) => !res.has(arr[code]) && res.set(arr[code], 1));
        },
    },
}
</script>

<style lang="less" scoped>
.page_box{
 width: 100%;
    padding: 20px ;
    background: #f6f6f6;
    box-sizing: border-box;
    height: 100vh;
    overflow: scroll;
} 
 .page_tabs{
        font-size: 16px;
        color: #0af;
        border-bottom: 2px solid #0af;
        height: 40px;
        line-height: 40px;
        width: 104px;
        box-sizing: border-box;
        text-align: center;
        margin-bottom: 15px;
    }
.statis_mian{
    width: 100%;
    box-sizing: border-box;
    overflow-y: auto;
    padding:5px 20px 30px; 
    background: #fff;
  
    .table_tit{
        font-size: 18px;
        font-weight: 600;
        margin: 20px 0;
    }
    
    .el-table{
        font-size: 13px;

        /deep/thead{
            color: #333;

        }
    }
}
.pageBox {
        display: flex;
        justify-content: space-between;
        margin-top: 20px;
    }
      .head_btn{
        width: 100%;
        text-align: left;
        margin: 20px 0; 
        span{
            margin: 0 10px ;
        }
    }
</style>